package monsmon.term;

import java.awt.event.KeyEvent;
import java.lang.reflect.*;

public class Key{

	public static final char
		K_LEFT				=	0x0100,
		K_RIGHT				=	0x0101,
		K_UP				=	0x0102,
		K_DOWN				=	0x0103,
		K_ESCAPE			= 	0x0104,
		K_HOME				=	0x0105,
		K_INSERT			=	0x0106,
		K_DELETE			=	0x0107,
		K_END				=	0x0108,
		K_TAB				=	0x0109,
		K_F1				=	0x010A,
		K_F2				=	0x010B,
		K_F3				=	0x010C,
		K_F4				=	0x010D,
		K_F5				=	0x010E,
		K_F6				=	0x010F,
		K_F7				=	0x0110,
		K_F8				=	0x0111,
		K_F9				=	0x0112,
		K_F10				=	0x0113,
		K_F11				=	0x0114,
		K_F12				=	0x0115;

	public static final int ALT_MASK 	=	0x010000,
	      			META_MASK	= 	0x020000,
				SHIFT_MASK	= 	0x040000,
				CTRL_MASK	= 	0x080000;
	
	public static final int BAD_KEY		=	0xBADBEEF1;

	public final boolean alt, meta, shift, ctrl;
	public final char c;
	public final int key;

	public Key(char c, boolean alt, boolean ctrl, 
			boolean meta, boolean shift){
		this.c = c;
		this.alt = alt;
		this.ctrl = ctrl;
		this.meta = meta;
		this.shift = shift;
		int mask = (alt ? ALT_MASK : 0) | (meta ? META_MASK : 0) |
			(shift ? SHIFT_MASK : 0) | (ctrl ? CTRL_MASK : 0);
		key = mask + c;
	}

	public Key(KeyEvent e){
		this(e.getKeyChar(), e.isAltDown(),
			e.isControlDown(), e.isMetaDown(), e.isShiftDown());
			
	}
	
	public static int to_key(char c, boolean alt, boolean ctrl, 
			boolean meta, boolean shift){
		return c + (alt ? ALT_MASK : 0) | (meta ? META_MASK : 0) |
			(shift ? SHIFT_MASK : 0) | (ctrl ? CTRL_MASK : 0);
	}
	
	public static int to_key(String sc, boolean alt, boolean ctrl, 
			boolean meta, boolean shift){
		if(!sc.startsWith("K_")) return BAD_KEY;
		try{
			Class ths = Key.class;
			Field k = ths.getField(sc);
			return to_key(k.getChar(null), alt, ctrl, meta, shift);
		}catch(NoSuchFieldException ex){
			System.err.print("Bad key string: "+sc);
			return BAD_KEY;
		}catch(Exception ex){
			ex.printStackTrace();
			return BAD_KEY;
		}
	}
	
}
